<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useSidebarStore } from '@/stores/sidebar'
import { getUserInfo, logout } from '@/api'
import { ElMessage } from 'element-plus'
import router from '@/router'
import type { UserInfo } from '@/types/Login'
import { ArrowDown } from '@element-plus/icons-vue'
import { updateUserPwdAsync, updateUserAsync } from '@/api/services/UserService'
import type { UpdateUserPwdAsyncParams, UpdateUserAsyncParams } from '@/types/User'

const sidebarStore = useSidebarStore()
const userInfo = ref<UserInfo | null>(null)
const updatePwdDialogVisible = ref(false)
const updatePwdForm = reactive({
  password: '',
  newPassword: '',
  confirmPassword: ''
})
const updatePwdLoading = ref(false)

// 个人信息对话框状态
const profileDialogVisible = ref(false)
const profileForm = reactive({
  account: '',
  realName: '',
  phone: '',
  email: '',
  avatarUrl: ''
})
const profileLoading = ref(false)

// 头像上传相关
const avatarFile = ref<File | null>(null)
const avatarPreviewUrl = ref('')
const avatarPreviewVisible = ref(false)

// 打开头像预览
const openAvatarPreview = () => {
  if (avatarPreviewUrl.value || profileForm.avatarUrl) {
    avatarPreviewVisible.value = true
  }
}

// 关闭头像预览
const closeAvatarPreview = () => {
  avatarPreviewVisible.value = false
}

// 处理头像选择
const handleAvatarSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }
    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过5MB')
      return
    }

    avatarFile.value = file
    // 创建预览URL
    avatarPreviewUrl.value = URL.createObjectURL(file)
    // 更新表单中的头像URL（这里可以设置为预览URL，实际保存时需要上传到服务器）
    profileForm.avatarUrl = avatarPreviewUrl.value
  }
}

// 触发文件选择
const triggerFileInput = () => {
  const fileInput = document.getElementById('avatar-upload') as HTMLInputElement
  if (fileInput) {
    fileInput.click()
  }
}

// 获取用户信息
const loadUserInfo = () => {
  const info = getUserInfo()
  if (info) {
    userInfo.value = info
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    // 直接清除本地存储的用户信息和token，不需要请求后端
    logout()
    ElMessage.success('退出登录成功')
    // 清空本地用户信息
    userInfo.value = null
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    ElMessage.error('退出登录失败' + error)
  }
}

// 获取头像URL - 直接使用后端返回的完整URL
const getAvatarUrl = (avatarUrl: string | null): string => {
  return avatarUrl || ''
}

// 打开修改密码对话框
const openUpdatePwdDialog = () => {
  // 重置表单
  updatePwdForm.password = ''
  updatePwdForm.newPassword = ''
  updatePwdForm.confirmPassword = ''
  updatePwdDialogVisible.value = true
}

// 验证表单
const validateForm = (): boolean => {
  if (!updatePwdForm.password.trim()) {
    ElMessage.error('请输入当前密码')
    return false
  }
  if (!updatePwdForm.newPassword.trim()) {
    ElMessage.error('请输入新密码')
    return false
  }
  if (!updatePwdForm.confirmPassword.trim()) {
    ElMessage.error('请确认新密码')
    return false
  }
  if (updatePwdForm.newPassword !== updatePwdForm.confirmPassword) {
    ElMessage.error('新密码和确认密码不一致')
    return false
  }
  return true
}

// 提交修改密码
const submitUpdatePwd = async () => {
  if (!validateForm()) {
    return
  }

  if (!userInfo.value?.id) {
    ElMessage.error('用户信息获取失败')
    return
  }

  updatePwdLoading.value = true
  try {
    const params: UpdateUserPwdAsyncParams = {
      id: userInfo.value.id,
      password: updatePwdForm.password,
      newPassword: updatePwdForm.newPassword
    }

    const response = await updateUserPwdAsync(params)

    if (response.success) {
      ElMessage.success(response.message || '密码修改成功')
      updatePwdDialogVisible.value = false
      // 密码修改成功后退出到登录页
      setTimeout(() => {
        handleLogout()
      }, 1000)
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error: unknown) {
    // 直接显示后端返回的错误信息
    if (error && typeof error === 'object' && 'response' in error) {
      const axiosError = error as { response?: { data?: { message?: string } } }
      if (axiosError.response?.data?.message) {
        ElMessage.error(axiosError.response.data.message)
      } else {
        ElMessage.error('密码修改失败')
      }
    } else if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('密码修改失败')
    }
  } finally {
    updatePwdLoading.value = false
  }
}

// 打开个人信息对话框
const openProfileDialog = () => {
  if (!userInfo.value) {
    ElMessage.error('用户信息获取失败')
    return
  }

  // 填充表单数据，不包括密码
  profileForm.account = userInfo.value.account || ''
  profileForm.realName = userInfo.value.realName || ''
  profileForm.phone = userInfo.value.phone || ''
  profileForm.email = userInfo.value.email || ''
  profileForm.avatarUrl = userInfo.value.avatarUrl || ''

  // 重置头像预览
  avatarFile.value = null
  avatarPreviewUrl.value = ''

  profileDialogVisible.value = true
}

// 验证个人信息表单
const validateProfileForm = (): boolean => {
  if (!profileForm.account.trim()) {
    ElMessage.error('请输入账号')
    return false
  }
  if (!profileForm.realName.trim()) {
    ElMessage.error('请输入真实姓名')
    return false
  }
  return true
}

// 提交个人信息修改
const submitProfile = async () => {
  if (!validateProfileForm()) {
    return
  }

  if (!userInfo.value?.id) {
    ElMessage.error('用户信息获取失败')
    return
  }

  profileLoading.value = true
  try {
    const params: UpdateUserAsyncParams = {
      id: userInfo.value.id,
      userCode: userInfo.value.userCode || '',
      account: profileForm.account,
      realname: profileForm.realName,
      phone: profileForm.phone,
      email: profileForm.email,
      status: 1, // 默认状态为1（启用）
      avatarUrl: profileForm.avatarUrl
    }

    const response = await updateUserAsync(params)

    if (response.success) {
      ElMessage.success(response.message || '个人信息修改成功')
      profileDialogVisible.value = false
      // 更新本地用户信息
      loadUserInfo()
    } else {
      ElMessage.error(response.message || '个人信息修改失败')
    }
  } catch (error: unknown) {
    // 直接显示后端返回的错误信息
    if (error && typeof error === 'object' && 'response' in error) {
      const axiosError = error as { response?: { data?: { message?: string } } }
      if (axiosError.response?.data?.message) {
        ElMessage.error(axiosError.response.data.message)
      } else {
        ElMessage.error('个人信息修改失败')
      }
    } else if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('个人信息修改失败')
    }
  } finally {
    profileLoading.value = false
  }
}

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      openProfileDialog()
      break
    case 'updatePwd':
      openUpdatePwdDialog()
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<template>
  <div class="header-content">
    <div class="header-left">
      <el-radio-group v-model="sidebarStore.isCollapse" size="small">
        <el-radio-button :label="false">展开</el-radio-button>
        <el-radio-button :label="true">收起</el-radio-button>
      </el-radio-group>
    </div>
    <div class="header-center">
      <h2>存储管理系统</h2>
    </div>
    <div class="header-right">
      <!-- 用户信息区域 -->
      <div v-if="userInfo" class="user-info">
        <el-dropdown @command="handleCommand">
          <div class="user-avatar">
            <el-avatar :size="32" :src="getAvatarUrl(userInfo.avatarUrl)" :alt="userInfo.realName">
              {{ userInfo.realName?.charAt(0) || userInfo.account?.charAt(0) }}
            </el-avatar>
            <span class="user-name">{{ userInfo.realName || userInfo.account }}</span>
            <el-icon><arrow-down /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="updatePwd">修改密码</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="updatePwdDialogVisible" title="修改密码" width="500px"
      :before-close="() => updatePwdDialogVisible = false">
      <el-form :model="updatePwdForm" label-width="100px">
        <el-form-item label="当前密码">
          <el-input v-model="updatePwdForm.password" type="password" placeholder="请输入当前密码" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="updatePwdForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="updatePwdForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updatePwdDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="updatePwdLoading" @click="submitUpdatePwd">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 个人信息对话框 -->
    <el-dialog v-model="profileDialogVisible" title="个人信息" width="600px"
      :before-close="() => profileDialogVisible = false">
      <div class="profile-dialog-content">
        <!-- 左侧头像区域 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <el-avatar :size="150" :src="avatarPreviewUrl || getAvatarUrl(profileForm.avatarUrl)"
              :alt="profileForm.realName" class="profile-avatar" @click="openAvatarPreview">
              {{ profileForm.realName?.charAt(0) || profileForm.account?.charAt(0) }}
            </el-avatar>
            <div class="avatar-actions">
              <el-button type="primary" size="small" @click="triggerFileInput">
                选择头像
              </el-button>
              <input id="avatar-upload" type="file" accept="image/*" style="display: none"
                @change="handleAvatarSelect" />
            </div>
            <p class="avatar-hint">支持 JPG、PNG 格式，大小不超过 5MB</p>
          </div>
        </div>

        <!-- 右侧个人信息区域 -->
        <div class="info-section">
          <div class="info-card">
            <h3 class="info-title">基本信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <label class="info-label">账号</label>
                <div class="info-value">
                  <el-input v-model="profileForm.account" placeholder="请输入账号" size="small" />
                </div>
              </div>
              <div class="info-item">
                <label class="info-label">真实姓名</label>
                <div class="info-value">
                  <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" size="small" disabled />
                </div>
              </div>
              <div class="info-item">
                <label class="info-label">手机号</label>
                <div class="info-value">
                  <el-input v-model="profileForm.phone" placeholder="请输入手机号" size="small" />
                </div>
              </div>
              <div class="info-item">
                <label class="info-label">邮箱</label>
                <div class="info-value">
                  <el-input v-model="profileForm.email" placeholder="请输入邮箱" size="small" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="profileDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="profileLoading" @click="submitProfile">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 头像预览对话框 -->
    <el-dialog v-model="avatarPreviewVisible" title="头像预览" width="400px" align-center
      :before-close="closeAvatarPreview">
      <div class="avatar-preview-container">
        <img :src="avatarPreviewUrl || getAvatarUrl(profileForm.avatarUrl)" :alt="profileForm.realName"
          class="avatar-preview-image" />
      </div>
      <template #footer>
        <el-button @click="closeAvatarPreview">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  width: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  display: flex;
  align-items: center;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-center h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: #f5f7fa;
}

.user-name {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

:deep(.el-dropdown-menu__item) {
  font-size: 14px;
}

:deep(.el-avatar) {
  border: 1px solid #e4e7ed;
}

/* 个人信息对话框样式 */
.profile-dialog-content {
  display: flex;
  gap: 24px;
  min-height: 300px;
}


.info-section {
  flex: 1;
  min-width: 0;
}

.info-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.info-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-label {
  flex: 0 0 80px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  text-align: right;
}

.info-value {
  flex: 1;
  min-width: 0;
}

.info-value :deep(.el-input) {
  width: 100%;
}

.info-value :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  box-shadow: none;
}

.info-value :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.info-value :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 头像预览样式 */
.avatar-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.avatar-preview-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

/* 调整头像区域样式使其更大更居中 */
.avatar-section {
  flex: 0 0 220px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  width: 100%;
}

.profile-avatar {
  border: 4px solid #409eff;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.25);
  transition: all 0.3s ease;
  cursor: pointer;
}

.profile-avatar:hover {
  transform: scale(1.08);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.35);
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  width: 100%;
}

.avatar-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin: 0;
  line-height: 1.4;
  max-width: 180px;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .profile-dialog-content {
    flex-direction: column;
    gap: 20px;
  }

  .avatar-section {
    flex: none;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-label {
    flex: none;
    text-align: left;
  }
}
</style>
